package com.dfqy.controller;

import com.dfqy.pojo.Admin;
import com.dfqy.service.AdminService;
import com.dfqy.util.PasswordUtil;
import com.dfqy.vo.Page;
import com.dfqy.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;


    @RequestMapping(value = "alladmin")
    public Page<Admin> paging(@RequestParam(defaultValue = "1") int page, int limit, String uname){
        Page<Admin> adminPage = adminService.paging(page,limit,uname);
        return adminPage;
    }

    @PostMapping(value = "/addadmin",produces = "application/json;charset=UTF-8")
    public Result add(@RequestBody Admin admin){

        int r = adminService.add(admin);
        if (r > 0)
            return Result.success();
        return Result.error("新增失败");
    }

    @RequestMapping(value = "/findadmin/{id}",produces = "application/json;charset=UTF-8")
    public Result findAdv(@PathVariable long id){
        System.out.println("要修改的id是："+id);
        Admin user = adminService.getInfoById(id);
        return user == null ? Result.error("该管理员不存在") : Result.success(user);
    }

    @RequestMapping(value = "/updateadmin",produces = "application/json;charset=UTF-8")
    public Result update(@RequestBody Admin admin){

        String pass = admin.getPass();
        String encrypt = PasswordUtil.hashPassword(pass);
        admin.setPass(encrypt);
        System.out.println(encrypt);
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        String encode = encoder.encode(pass);
//        admin.setPass(encode);
//        System.out.println(encode);

        int r = adminService.update(admin);
        if (r > 0)
            return Result.success();
        return Result.error("修改失败");
    }

    @RequestMapping(value = "/deladmin",produces = "application/json;charset=UTF-8")
    public Result del(long ...id){
        int r = adminService.delete(id);
        return r > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }
}
